import * as THREE from './js/three.module.js';
import { OrbitControls } from './js/OrbitControls.js';
import { CSS2DObject, CSS2DRenderer } from './js/CSS2DRenderer.js';

var objectsList = [];

class Object {
    constructor(name, x, y, z, w, h, texture) {
        if (arguments.length > 2) {
            const geometry1 = new THREE.PlaneGeometry(w, h);
            const texture1 = loader.load(texture);
            const material1 = new THREE.MeshBasicMaterial({
                map: texture1,
            });
            const cube = new THREE.Mesh(geometry1, material1);
            cube.material.depthTest = false;
            cube.renderOrder = 99;
            scene.add(cube);
            cube.position.set(x, y, z);
            cube.onBeforeRender = function (render, scene, camera) {
                cube.lookAt(camera.position);
            }
            cube.material.transparent = true;
            this.mesh = cube;
        } else {
            this.mesh = x;
        }
        this.name = name;
        this.mesh.name = name;
        this.clickcallback = function () { };
    }
    addClickListener(callback) {
        this.clickcallback = callback;
    }
    removeClickListenner() {
        this.clickcallback = function () { };
    }
    setImage(texture) {
        this.mesh.material.map = new THREE.TextureLoader().load(texture);
    }
}

var scene = new THREE.Scene();


var width = window.innerWidth; //窗口宽度
var height = window.innerHeight; //窗口高度
//创建相机对象
var camera = new THREE.PerspectiveCamera(45, width / height, 1, 1000);
camera.position.set(100, 0, 0); //设置相机位置
camera.lookAt(scene.position); //设置相机方向(指向的场景对象)position

// 实例化css2d的渲染器
const labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(labelRenderer.domElement);
//设置样式
labelRenderer.domElement.style.position = 'fixed';
labelRenderer.domElement.style.top = '0px';
labelRenderer.domElement.style.left = '0px';
labelRenderer.domElement.style.zIndex = '10';//设置层级

/**
 * 创建渲染器对象
 */
var renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);//设置渲染区域尺寸
renderer.setClearColor(0xb9d3ff, 1); //设置背景颜色
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
document.getElementById("vrview").appendChild(renderer.domElement);


const controls = new OrbitControls(camera, labelRenderer.domElement);
controls.enableDamping = true;
controls.enablePan = false;
controls.enableZoom = true;
controls.zoomSpeed = 3;
controls.rotateSpeed = 1;


function render() {//循环函数
    if (nowSelectObject != "null") {
        for (let i = 0; i < objectsList.length; i++) {
            if (objectsList[i].name == nowSelectObject) {
                objectsList[i].clickcallback();
                break;
            }
        }
        nowSelectObject = 'null';
    }
    controls.update();
    renderer.render(scene, camera);//执行渲染操作
    labelRenderer.render(scene, camera);
    camera.updateMatrix();
    requestAnimationFrame(render)


}
render();

//窗口大小自适应
window.addEventListener("resize", function () {
    let w = window.innerWidth;
    let h = window.innerHeight;
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
    renderer.setSize(w, h);
    labelRenderer.setSize(w, h);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

});

window.addEventListener("orientationchange", function () {
    let w = window.innerWidth;
    let h = window.innerHeight;
    camera.aspect = w / h;
    camera.updateProjectionMatrix();
    renderer.setSize(w, h);
    labelRenderer.setSize(w, h);
    renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));

});

const ray = new THREE.Raycaster();
const mouse = new THREE.Vector2();
let x = 0;
let y = 0;
let w = 0;
let h = 0;
labelRenderer.domElement.addEventListener('mousemove', (event) => {
    x = event.offsetX;
    y = event.offsetY;
    w = renderer.domElement.offsetWidth;
    h = renderer.domElement.offsetHeight;
    mouse.x = x / w * 2 - 1;
    mouse.y = -y * 2 / h + 1;
});

var nowSelectObject = 'null';
labelRenderer.domElement.addEventListener('click', (event) => {
    controls.enable(true);
    ray.setFromCamera(mouse, camera);
    const intersection = ray.intersectObject(scene);
    if (intersection.length != 0) {
        if (intersection[0].object.name == 'ballview' && intersection.length > 1) {
            nowSelectObject = intersection[1].object.name;
        } else {
            nowSelectObject = intersection[0].object.name;
        }
    } else {
        nowSelectObject = 'null';
    }
})

function addObject(object) {
    objectsList.push(object);
    scene.add(object.mesh);
}
function removeObject(name) {
    for (let i = 0; i < objectsList.length; i++) {
        if (name == objectsList[i].name) {
            objectsList[i].mesh.geometry.dispose();
            objectsList[i].mesh.material.dispose();
            scene.remove(objectsList[i].mesh);
            objectsList = objectsList.splice(i, 1);
            break;
        }
    }
}

const geom = new THREE.SphereGeometry(200, 64, 64);
// 纹理
const loader = new THREE.TextureLoader();
const texture = loader.load('./img/1.jpg');
// 材质
const material = new THREE.MeshBasicMaterial({
    map: texture,
    side: THREE.BackSide
});
const earth = new THREE.Mesh(geom, material);
earth.material.transparent = true;
scene.add(earth);

objectsList.push(new Object('ballview', earth));
function setBallViewImage(texture) {
    earth.material.map = new THREE.TextureLoader().load(texture);
}



const earthDiv = document.createElement('div');
earthDiv.className = "label";
earthDiv.innerHTML = "<img src=\"./img/1.jpg\" draggable=\"false\" width=\"200\"/><br/><br/><div align=\"center\"><button style=\"display: block;background: url(./img/1.jpg);width:150px;height:60px\"></div>";
const earthLabel = new CSS2DObject(earthDiv);
earthLabel.position.set(-200, 50, 0);//相对于父级元素的位置
scene.add(earthLabel);
earthLabel.element.addEventListener('pointerdown', function (event) {
    setBallViewImage('./img/2.jpg');
});




export { Object, THREE, addObject, removeObject, earth, setBallViewImage };